let timeout = 10000

const request = config => {
	// 是否需要设置 token
	config.header = config.header || {}
	if (uni.getStorageSync('token')&&config.headers.isToken) {
		config.header['Authorization'] = 'Bearer ' + uni.getStorageSync('token')
		config.header['token'] =  uni.getStorageSync('token')
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	return new Promise((resolve, reject) => {
		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: 'https://nchc.vicp.cc/' + config.url,
				data: config.data,
				header: config.header,
				dataType: 'json'
			}).then(response => {
				let res = response.data
				let err = response.data
				const code = res.code 
				const msg = res.msg 
				if (code === 401) {
					uni.showModal({
						title:'提示',
						content: '登录状态已过期，您可以继续留在该页面，或者重新登录?',
						success: function (res) {
							if (res.confirm) {
								uni.reLaunch({
									url:'/pages/login/login'
								})
							} else if (res.cancel) {
								
							}
						}
					});
					reject('无效的会话，或者会话已过期，请重新登录。')
				}
				else if (code === 500) {
					uni.showToast({
						icon:'none',
						title:msg
					})
					reject(res)
				} 
				else if (code !== 0&&code!==1) {
					uni.showToast({
						icon:'none',
						title:msg
					})
					reject(res)
				}else{
					resolve(res)
				}
			})
			.catch(error => {
				// let {
				// 	message
				// } = error
				// if (message === 'Network Error') {
				// 	message = '后端接口连接异常'
				// } else if (message.includes('timeout')) {
				// 	message = '系统接口请求超时'
				// } else if (message.includes('Request failed with status code')) {
				// 	message = '系统接口' + message.substr(message.length - 3) + '异常'
				// }
				// toast(message)
				reject(error)
			})
	})
}

export default request
